<script lang="ts" setup>
import { reactive, ref } from "vue"
import { createRateApi, updateRateApi, getAmountRangesSearchApi } from "@/api/calculator"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"

interface Emits {
  (e: "success"): void
}

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance | null>(null)
const loading = ref<boolean>(false)
const visible = ref<boolean>(false)
const editData = ref<any>(undefined)

const formData = reactive({
  rate: "",
  month: "",
  rate_mode: "",
  range_id: "",
  range_name: "",
  date_range_id: ""
})

const formRules: FormRules = reactive({
  rate: [{ required: true, trigger: "blur", message: "请输入利率值" }],
  month: [{ required: true, trigger: "blur", message: "请选择生效月份" }],
  rate_mode: [{ required: true, trigger: "blur", message: "请选择利率模式" }],
  range_name: [{ required: true, trigger: "blur", message: "请选择金额区间" }]
})

// 利率模式选项
const rateModeOptions = [
  { label: "固定比例", value: "FIXED" },
  // { label: "浮动", value: "FLOAT" },
  { label: "固定金额", value: "FIXED_AMOUNT" }
]

// 获取下个月的第一天
const getNextMonth = () => {
  const now = new Date()
  return new Date(now.getFullYear(), now.getMonth() + 1, 1)
}

// 禁用当月及之前的月份
const disabledDate = (time: Date) => {
  const nextMonth = getNextMonth()
  return time < nextMonth
}

// 金额区间搜索相关
const querySearchAsync = (queryString: string, cb: (suggestions: any[]) => void) => {
  if (queryString) {
    const amount = parseFloat(queryString)
    if (!isNaN(amount)) {
      getAmountRangesSearchApi({ amount })
        .then((res: any) => {
          const suggestions = res.data.map((range: any) => ({
            value: `${range.min_amount}-${range.max_amount}`,
            id: range.range_id,
            ...range
          }))
          cb(suggestions)
        })
        .catch(() => {
          cb([])
        })
    } else {
      cb([])
    }
  } else {
    cb([])
  }
}

const handleAmountRangeSelect = (item: any) => {
  formData.range_id = item.id
  formData.range_name = item.value
}

// 重置表单
const resetForm = () => {
  formData.rate = ""
  formData.month = ""
  formData.rate_mode = ""
  formData.range_id = ""
  formData.range_name = ""
  formData.date_range_id = ""
  formRef.value?.resetFields()
}

// 打开对话框 - 新增
const openAdd = () => {
  editData.value = undefined
  resetForm()
  visible.value = true
}

// 打开对话框 - 编辑
const openEdit = (data: any) => {
  editData.value = data
  formData.rate = data.rate || ""
  formData.month = data.month || ""
  formData.rate_mode = data.rate_mode || ""
  formData.range_id = data.range_id || ""
  formData.range_name = data.amount_range || ""
  formData.date_range_id = data.date_range_id || ""
  visible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      const baseData = {
        rate: Number(formData.rate),
        rate_mode: formData.rate_mode as "FIXED" | "FLOAT" | "FIXED_AMOUNT",
        date_range_id: Number(formData.date_range_id) || 1,
        rate_id: editData.value?.rate_id || 1
      }

      const apiCall = editData.value
        ? updateRateApi({
            ...baseData,
            range_id: Number(formData.range_id)
          })
        : createRateApi(baseData)

      apiCall
        .then(() => {
          ElMessage.success(editData.value ? "修改成功" : "新增成功")
          emit("success")
          handleClose()
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 暴露方法给父组件调用
defineExpose({
  openAdd,
  openEdit
})
</script>

<template>
  <el-dialog v-model="visible" :title="editData ? '修改利率' : '新增利率'" width="500px" @close="handleClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
      v-loading="loading"
    >
      <el-form-item prop="rate" label="利率值">
        <el-input v-model="formData.rate" placeholder="请输入利率值" type="number" />
      </el-form-item>
      <el-form-item prop="month" label="生效月份">
        <el-date-picker
          v-model="formData.month"
          type="month"
          placeholder="请选择生效月份"
          format="YYYY-MM-01"
          value-format="YYYY-MM-01"
          :disabled-date="disabledDate"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item prop="rate_mode" label="利率模式">
        <el-select v-model="formData.rate_mode" placeholder="请选择利率模式" style="width: 100%">
          <el-option
            v-for="option in rateModeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="range_name" label="金额区间">
        <el-autocomplete
          v-model="formData.range_name"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入搜索金额区间"
          @select="handleAmountRangeSelect"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确认</el-button>
    </template>
  </el-dialog>
</template>
